package com.example.app.service;

import com.example.app.config.AuthConfig;
import com.example.app.entity.ReqData;
import com.example.app.util.HttpClient;
import com.example.app.util.SignHelper;
import com.example.app.util.TimeHelper;
import com.example.app.util.ToolHelper;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class AuthService {
    private static  AuthConfig authConfig;


    public AuthService(AuthConfig authConfig) {
        this.authConfig=authConfig;
    }

    /**
     * 签名
     * @return
     * @throws Exception
     */
    public ReqData getSign(){
        return getObject(authConfig.getAppId(),authConfig.getAppSecret(),null);
    }

    /**
     * 签名
     * @param map 传入参数
     * @return
     */
    public ReqData getSign(Map<String,String>  map){
        return getObject(authConfig.getAppId(),authConfig.getAppSecret(),map);
    }
    public ReqData getSign(Object  map){
        return getObject(authConfig.getAppId(),authConfig.getAppSecret(),JSONObject.fromObject(map));
    }
    /**
     * 赋值请求对象
     * @param appID
     * @param appSecret
     * @return
     */
    public ReqData getObject(String appID, String appSecret,Map<String,String> map) {
        ReqData reqData = new ReqData();
        reqData.setAppid(appID);
        reqData.setNonceStr(ToolHelper.getUUID());
        reqData.setTimeTemp(TimeHelper.getCurrentTimes()+"");
        reqData.setReq(map);
        String sign  = null;
        try {
            sign = SignHelper.getSignature(JSONObject.fromObject(reqData), appSecret);
        } catch (Exception e) {
            e.printStackTrace();
        }
        reqData.setSign(sign);
        return reqData;
    }

    /**
     * 获取用户信息
     * @return
     */
    public Object getUserInfo() {
        ReqData sign = getSign();
        Map<String, String> map = new HashMap<>();
        /**
         * 从session中获取code
         */
        String code = (String) HttpClient.session.getAttribute(authConfig.getResponseType());
        map.put("authCode",code);
        sign.setReq(map);
        String client = HttpClient.postClient(authConfig.getAuthRest() + "getAuthCode", JSONObject.fromObject(sign).toString());
        JSONObject parse = JSONObject.fromObject(client);
        return parse;
    }
}
